//
//  KSingingRecordViewCtr.m
//  CCBbelefitLife
//
//  Created by liurg on 16/1/3.
//  Copyright © 2016年 liurg. All rights reserved.
//

#import "KSingingRecordViewCtr.h"
#import "CustomPickerBottomView.h"
#import "Music.h"
#import <AudioToolbox/AudioToolbox.h>
#import "lame.h"
#import "EQDB.h"
#import "EQPlayer.h"
#import "Utilities.h"
#import "NGVolumeControl.h"
#import "CustomPickerBottomView.h"
#import "SingRecordFinshView.h"

#define  TempRecordPath  @"tempRecordPath"
//#define  TempRecordName  @"tempQingChangName.caf"
#define  DocRecordPath  @"docRecordPath"
#define  DocRecordName  @"docQingChangName"

@interface KSingingRecordViewCtr ()<UITableViewDataSource , UITableViewDelegate,CustomPickerBottomViewDelegate,UIAlertViewDelegate>{
    
    NSMutableArray *timeArray;
    NSMutableDictionary *LRCDictionary;
    NSUInteger lrcLineNumber;
    UITableView *lrcTableView;
    AVAudioPlayer *audioPlayer;
    AVAudioPlayer *accAudioPlayer;
    NSMutableArray *musicArray;
    BOOL isPlay;
    BOOL isCircle;
    BOOL isOrigin;
    BOOL isPopular;
    BOOL isRock;
    BOOL musicTableViewHidden;
    float tempVolume;
    NSInteger seleEq;
    Music *currentMusic;
    NSUInteger musicArrayNumber;
    UIButton * circleBtn;
    UIButton * playBtn;
    UIButton * rightBtn;
    UISlider * progressSlider;
    UIScrollView *scrollView;
    NSMutableArray * seleArray;
    NSURL *fileURL;
    UIButton *leftBtn;
    BOOL isBack;
    UISlider  *volumeSlider;
    NGVolumeControl * volumeControl;
}
@property(nonatomic,retain) NSTimer *refreshTimer;
@property(nonatomic,retain) UILabel *showProgressLab;
@property(nonatomic,retain) UIButton *bgContentBtn;
@property(nonatomic,assign) BOOL isRecording;
@property(nonatomic,assign) CGFloat sampleRate;
@property(nonatomic,assign) AVAudioQuality quality;
@property(nonatomic,assign) NSInteger formatIndex;
@property(nonatomic,retain) NSString *recordedFile;
@property(nonatomic,retain) AVAudioRecorder *recorderAudio;
@property(nonatomic,retain) NSTimer *recTimer;
@property(nonatomic,retain) NSTimer *timer;

@property(nonatomic,retain) UILabel *recDesLab;
@property(nonatomic,retain) NSString *recordedFileName;
@property(nonatomic,retain) NSString *mp3FileName;
//@property(nonatomic,retain) NSString *musicName;

@end

@implementation KSingingRecordViewCtr

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我要K歌";
    isOrigin = YES;
    isPopular = NO;
    isRock = NO;
    seleEq = 0;
    isBack = NO;
    seleArray = [[NSMutableArray alloc]initWithCapacity:10];
    
#warning 停止外围播放音频  隐藏返回按钮
    [[DOUAudioEventLoop sharedEventLoop] stop];
    
    [self configData];
    [self setupView];
    
}



- ( void ) viewWillAppear:( BOOL ) animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    self.tabBarController.tabBar.hidden = YES;
    [self buildNavView];
    // [ShareAppDelegate.ApptabBar hideSysTabar];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    
}


-(void)buildNavView{
    //导航栏右侧按钮
    //    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    //    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    //    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    //    [rightBtn setTitle:@"伴唱" forState:0];
    //    [rightBtn setTitleColor:[UIColor whiteColor] forState:0];
    //    [rightBtn addTarget:self action:@selector(handleConvert) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"" highIcon:@"" target:self action:nil];
    
}

-(void)backBtnAction{
    isBack = YES;
    [audioPlayer stop];
    audioPlayer = nil;
    if (_recorderAudio != nil )
    {
        [_recorderAudio stop];
        _recorderAudio = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
    //  [[UIApplication sharedApplication] setStatusBarHidden:NO];
}


-(void)setupView
{
    
    UIImageView *backViewImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth, mainScreenHeight-64)];
    backViewImg.image = [UIImage imageNamed:@"清唱背景"];
    [self.view addSubview:backViewImg];
    
    UILabel *recordDesLab = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, mainScreenWidth-20, 28)];
    recordDesLab.text = [NSString stringWithFormat:@"%@--%@",_musicName,_singerName];
    recordDesLab.textAlignment = NSTextAlignmentCenter;
    recordDesLab.textColor = [UIColor whiteColor];
    recordDesLab.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:recordDesLab];
    
    _currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenWidth*0.5-65, 43, 85, 20)];
    _currentTimeLabel.textAlignment = NSTextAlignmentRight;
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_currentTimeLabel];
    
    _totalTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenWidth*0.5+25, 43, 50, 20)];
    _totalTimeLabel.textAlignment = NSTextAlignmentLeft;
    _totalTimeLabel.textColor = [UIColor whiteColor];
    _totalTimeLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:_totalTimeLabel];
    
    UIButton *recordMaiBtn = [[UIButton alloc]initWithFrame:CGRectMake(70, 80, mainScreenWidth-70*2, mainScreenWidth-80*2)];
    [self.view addSubview:recordMaiBtn];
    _bgContentBtn = recordMaiBtn;
    [recordMaiBtn setBackgroundImage:[UIImage imageNamed:@"kg_preload"] forState:UIControlStateNormal];
    
    _showProgressLab = [[UILabel alloc]initWithFrame:CGRectMake(recordMaiBtn.width/2-40, recordMaiBtn.height/2-25, 50, 50)];
    _showProgressLab.text = @"20";
    _showProgressLab.textColor = [UIColor whiteColor];
    _showProgressLab.font = [UIFont systemFontOfSize:40];
    
    UILabel *baiLab = [[UILabel alloc]initWithFrame:CGRectMake(_showProgressLab.righX, _showProgressLab.y+15, 30, 30)];
    baiLab.textColor = [UIColor whiteColor];
    baiLab.text = @"%";
    baiLab.font = [UIFont systemFontOfSize:25];
    [recordMaiBtn addSubview:baiLab];
    [recordMaiBtn addSubview:_showProgressLab];
    
    //构建底部栏
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-64, mainScreenWidth, 50)];
    bottomView.backgroundColor = JYColor(238, 239, 241);
    [self.view addSubview:bottomView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 10, 1, 30)];
    lineView.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView];
    
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 10, 1, 30)];
    lineView1.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView1];
    
    
    leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:leftBtn];
    UIImageView *flowerImg = [[UIImageView alloc]initWithFrame:CGRectMake((leftBtn.width-20)/2, 15, 20, 20)];
    flowerImg.image = [UIImage imageNamed:@"qc_flower"];
    [leftBtn addSubview:flowerImg];
    
    UIButton *middleBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:middleBtn];
    [middleBtn addTarget:self action:@selector(finishDecod) forControlEvents:UIControlEventTouchUpInside];
    UILabel *desLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 15, middleBtn.width, 20)];
    desLab.textAlignment = NSTextAlignmentCenter;
    desLab.text = @"完成录音";
    [middleBtn addSubview:desLab];
    
    rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(isShowSlider) forControlEvents:UIControlEventTouchUpInside];
    //    volumeControl = [[NGVolumeControl alloc] initWithFrame:CGRectMake((rightBtn.width-20)/2, 7.5, 35, 35)];
    //    volumeControl.volume = 1;
    //   [rightBtn addSubview:volumeControl];
    [rightBtn setImage:[UIImage imageNamed:@"ringingBell.png"] forState:UIControlStateNormal];
    //  [rightBtn setBackgroundImage:[UIImage imageNamed:@"ringingBell.png"] forState:UIControlStateNormal];
    volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(rightBtn.x+20, mainScreenHeight-50-150, 150, 40)];
    //  [volumeSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateNormal];
    volumeSlider.thumbTintColor=JYColor(233, 131, 46);
    volumeSlider.tag = 106;
    //设置已经滑过一端滑动条背景图片，会覆盖之前之前的颜色，以下相同
    volumeSlider.minimumTrackTintColor= [UIColor redColor];   //JYColor(105, 215, 16);
    //设置未滑过一端滑动条颜色
    volumeSlider.maximumTrackTintColor= [UIColor blackColor];   //JYColor(246, 246, 246);
    [volumeSlider addTarget:self action:@selector(adjustVolume)
           forControlEvents:UIControlEventValueChanged];
    volumeSlider.minimumValue = 0.0f;
    volumeSlider.maximumValue = 1.0;
    volumeSlider.value = 0.5;
    [self.view addSubview:volumeSlider];
    
    volumeSlider.minimumValue = 0.f;
    volumeSlider.maximumValue = 1.f;
    volumeSlider.transform = CGAffineTransformMakeRotation(M_PI * -0.5);;
    volumeSlider.center = CGPointMake(rightBtn.x+rightBtn.width/2, mainScreenHeight-50-150.f);
    volumeSlider.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    [self.view bringSubviewToFront:volumeSlider];
    volumeSlider.hidden = YES;
    
    
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if(session == nil)
        NSLog(@"Error creating session: %@", [sessionError description]);
    else
        [session setActive:YES error:nil];
    _sampleRate  = 44100.0;
    _formatIndex = kAudioFormatLinearPCM;
    _quality     =  AVAudioQualityMedium;
    UInt32 doChangeDefaultRoute = 1;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
    //播放本地音乐
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //初始化要加载的曲目
        if(_musicUrl.length > 0){
            NSURL *url = nil;
            if(![_musicUrl containsString:@"%"]){
                url = [[NSURL alloc]initWithString:[_musicUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            }else{
                url = [[NSURL alloc]initWithString:_musicUrl];
            }
            
            NSRange musicRange = [_musicUrl rangeOfString:@".com/"];
            NSString * temp = [_musicUrl substringFromIndex:musicRange.location+musicRange.length];
            NSData * audioData = [NSData dataWithContentsOfURL:url];
            
            //将数据保存到本地指定位置
            NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirPath , temp];
            fileURL = [NSURL fileURLWithPath:filePath];
            [audioData writeToFile:filePath atomically:YES];
            audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
            audioPlayer.volume = 1;
        }
        if(_accompanyUrl.length > 0){
            NSURL *accompany = [[NSURL alloc]initWithString:[_accompanyUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSRange accompanyRange = [_accompanyUrl rangeOfString:@".com/"];
            NSString * temp = [_musicUrl substringFromIndex:accompanyRange.location+accompanyRange.length];
            NSData * audioData = [NSData dataWithContentsOfURL:accompany];
            
            //将数据保存到本地指定位置
            NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *filePath = [NSString stringWithFormat:@"%@/%@", docDirPath , temp];
            fileURL = [NSURL fileURLWithPath:filePath];
            [audioData writeToFile:filePath atomically:YES];
            accAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
            
        }
        
        if(audioPlayer !=nil){
            dispatch_async(dispatch_get_main_queue(), ^{
                lrcTableView = [[UITableView alloc] initWithFrame:CGRectMake( 0.0 , 65 , mainScreenWidth , self.view.height - 164  ) style:UITableViewStylePlain];
                lrcTableView.backgroundColor = [UIColor clearColor];
                lrcTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
                // _chatTableView.allowsSelection = NO;
                lrcTableView.dataSource = self;
                lrcTableView.delegate = self;
                [self.view addSubview:lrcTableView];
                [self reBuildView];
                [leftBtn addTarget:self action:@selector(saveLeftBtnAction) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:volumeSlider];
            });
        }
    });
    
}

-(void)isShowSlider{
    volumeSlider.hidden = !volumeSlider.hidden;
    if (volumeSlider.hidden == NO) {
        [self.view bringSubviewToFront:volumeSlider];
        // [self insertSubview:volumeSlider aboveSubview:(UIView *)siblingSubview;
        
    }
}

-(void)reBuildView{
    
    [_bgContentBtn removeFromSuperview];
    
    isPlay = YES;
    isCircle = YES;
    lrcLineNumber = 0;
    musicTableViewHidden = YES;//初始化隐藏歌曲目录
    //    musicTableView.hidden = YES;
    //初始化歌词词典
    timeArray = [[NSMutableArray alloc] initWithCapacity:10];
    LRCDictionary = [[NSMutableDictionary alloc] initWithCapacity:10];
    [self recordSingMusic];
    [self initLRC];
    [audioPlayer play];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
                                              target:self
                                            selector:@selector(showTime)
                                            userInfo:nil
                                             repeats:YES];
}

-(void)configData{
    
    _refreshTimer = [NSTimer scheduledTimerWithTimeInterval:.05f
                                                     target:self
                                                   selector:@selector(timerRefresh)
                                                   userInfo:nil
                                                    repeats:YES];
}
-(void)saveLeftBtnAction{
    
    NSArray *titleArr = @[@"完成",@"重录",@"退出",@"取消"];
    CustomPickerBottomView *pickerBottomView = [[CustomPickerBottomView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-60*titleArr.count, mainScreenWidth, 60*titleArr.count) titleArr:titleArr];
    pickerBottomView.delegate = self;
}


//切换音频
-(void)cutMusicSize:(UIControl *)sender{
    seleEq = sender.tag;
    for(int i = 0;i< seleArray.count;i++){
        
        if(i == sender.tag){
            ((UIImageView *)seleArray[i]).hidden = NO;
        }else{
            ((UIImageView *)seleArray[i]).hidden = YES;
        }
    }
}

-(void)adjustVolume{
    audioPlayer.volume = volumeSlider.value;
}

-(void)timerRefresh{
    
    NSInteger progressInter = [_showProgressLab.text integerValue];
    progressInter = progressInter+1;
    if (progressInter>=99) {
        [_refreshTimer invalidate];
        _refreshTimer = nil;
    }
    _showProgressLab.text = [NSString stringWithFormat:@"%2ld",(long)progressInter];
    
    
}
-(void)ringingBellBtnAction{
    _soundSlider.hidden = !_soundSlider.hidden;
}
#pragma mark 得到歌词
- (void)initLRC {
    NSURL *lrcUrl = [[NSURL alloc]initWithString:[_lyrUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: lrcUrl cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
        if (error) {
        } else {
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"=======>%@",responseString);
            NSArray *array = [responseString componentsSeparatedByString:@"\n"];
            for (int i = 0; i < [array count]; i++) {
                NSString *linStr = [array objectAtIndex:i];
                NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
                if ([lineArray[0] length] > 8) {
                    NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];
                    NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];
                    if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
                        NSString *lrcStr = [lineArray objectAtIndex:1];
                        NSString *timeStr = [[lineArray objectAtIndex:0] substringWithRange:NSMakeRange(1, 5)];//分割区间求歌词时间
                        //把时间 和 歌词 加入词典
                        [LRCDictionary setObject:lrcStr forKey:timeStr];
                        [timeArray addObject:timeStr];//timeArray的count就是行数
                    }
                }
            }
        }
    }];
    
}
#pragma mark 动态显示歌词
- (void)displaySondWord:(NSUInteger)time {
    //    NSLog(@"time = %u",time);
    for (int i = 0; i < [timeArray count]; i++) {
        
        NSArray *array = [timeArray[i] componentsSeparatedByString:@":"];//把时间转换成秒
        NSUInteger currentTime = [array[0] intValue] * 60 + [array[1] intValue];
        if (i == [timeArray count]-1) {
            //求最后一句歌词的时间点
            NSArray *array1 = [timeArray[timeArray.count-1] componentsSeparatedByString:@":"];
            NSUInteger currentTime1 = [array1[0] intValue] * 60 + [array1[1] intValue];
            if (time > currentTime1) {
                [self updateLrcTableView:i];
                break;
            }
        } else {
            //求出第一句的时间点，在第一句显示前的时间内一直加载第一句
            NSArray *array2 = [timeArray[0] componentsSeparatedByString:@":"];
            NSUInteger currentTime2 = [array2[0] intValue] * 60 + [array2[1] intValue];
            if (time < currentTime2) {
                [self updateLrcTableView:0];
                //                NSLog(@"马上到第一句");
                break;
            }
            //求出下一步的歌词时间点，然后计算区间
            NSArray *array3 = [timeArray[i+1] componentsSeparatedByString:@":"];
            NSUInteger currentTime3 = [array3[0] intValue] * 60 + [array3[1] intValue];
            if (time >= currentTime && time <= currentTime3) {
                [self updateLrcTableView:i];
                break;
            }
            
        }
    }
}

#pragma mark 0.1秒一次更新 播放时间 播放进度条 歌词 歌曲 自动播放下一首
- (void)showTime {
    //动态更新进度条时间
    if ((int)audioPlayer.currentTime % 60 < 10) {
        _currentTimeLabel.text = [NSString stringWithFormat:@"正在录音 %d:0%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    } else {
        _currentTimeLabel.text = [NSString stringWithFormat:@"正在录音 %d:%d",(int)audioPlayer.currentTime / 60, (int)audioPlayer.currentTime % 60];
    }
    //
    if ((int)audioPlayer.duration % 60 < 10) {
        _totalTimeLabel.text = [NSString stringWithFormat:@"/%d:0%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    } else {
        _totalTimeLabel.text = [NSString stringWithFormat:@"/%d:%d",(int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60];
    }
    progressSlider.value = audioPlayer.currentTime / audioPlayer.duration;
    
    [self displaySondWord:audioPlayer.currentTime];//调用歌词函数
    if((audioPlayer.currentTime / audioPlayer.duration) > 0.97){
        _isRecording = NO;
        [_recTimer invalidate];
        _recTimer = nil;
        [_timer invalidate];
        _timer = nil;
        
        [audioPlayer stop];
        audioPlayer = nil;
        
        if (_recorderAudio != nil )
        {
            [_recorderAudio stop];
            _recorderAudio = nil;
        }
        _mp3FileName = [Utilities getDocmentSaveFilePathString:_musicName filePath:DocRecordPath];
        
        EQPlayer * player = [[EQPlayer alloc] init];
        
        SingRecordFinshView *singRecViewCtr = [[SingRecordFinshView alloc]initWithPlayer:player];
        singRecViewCtr.recordMusicPath = _mp3FileName;
        singRecViewCtr.eqcount = seleEq;
        singRecViewCtr.recordMusicName = _musicName;
        
        [self encodeMp3];
        [self.navigationController pushViewController:singRecViewCtr animated:YES];
    }
}


#pragma mark 动态更新歌词表歌词
- (void)updateLrcTableView:(NSUInteger)lineNumber {
    //    NSLog(@"lrc = %@", [LRCDictionary objectForKey:[timeArray objectAtIndex:lineNumber]]);
    //重新载入 歌词列表lrcTabView
    lrcLineNumber = lineNumber;
    [lrcTableView reloadData];
    //使被选中的行移到中间
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lineNumber inSection:0];
    [lrcTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    //    NSLog(@"%i",lineNumber);
}
#pragma mark 表视图
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [timeArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"LRCCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//该表格选中后没有颜色
    cell.backgroundColor = [UIColor clearColor];
    if (indexPath.row == lrcLineNumber) {
        cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
        cell.textLabel.textColor = [UIColor colorWithRed:104/255.0 green:214/255.0 blue:15/255.0 alpha:1.0];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    } else {
        cell.textLabel.text = LRCDictionary[timeArray[indexPath.row]];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:13];
    }
    cell.textLabel.backgroundColor = [UIColor clearColor];
    //        cell.textLabel.textColor = [UIColor blackColor];
    
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    
    //        [cell.contentView addSubview:lable];//往列表视图里加 label视图，然后自行布局
    return cell;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 35;
}
//选中后的响应函数
//- (void)playTable:(NSUInteger)tableNumber {
//    musicArrayNumber = tableNumber;
//    [self updatePlayerSetting];
//}
- (void)encodeMp3{
    if (!_isRecording)
    {
        [NSThread detachNewThreadSelector:@selector(convertToMp3) toTarget:self withObject:nil];
    }
}


- (void) convertToMp3
{
    // NSURL *recordedFileNameUrl = [NSURL fileURLWithPath:recordedFileName];
    @try {
        int read, write;
        
        FILE *pcm = fopen([_recordedFileName cStringUsingEncoding:1], "rb");  //source
        if(pcm == NULL){
            return;
        }
        fseek(pcm, 4*1024, SEEK_CUR);
        //skip file header
        FILE *mp3 = fopen([_mp3FileName cStringUsingEncoding:1], "wb");  //output
        if(mp3 == NULL){
            return;
        }
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, _sampleRate);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        [self performSelectorOnMainThread:@selector(convertMp3Finish)
                               withObject:nil
                            waitUntilDone:YES];
    }
}

-(void)recordSingMusic{
    
    if (!_isRecording&&!_recTimer)
    {
        NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [NSNumber numberWithFloat: _sampleRate],                  AVSampleRateKey,
                                  [NSNumber numberWithLong: _formatIndex],                   AVFormatIDKey,
                                  [NSNumber numberWithInt: 2],                              AVNumberOfChannelsKey,
                                  [NSNumber numberWithInt: _quality],                       AVEncoderAudioQualityKey,
                                  nil];
        
        // _recordedFile = [[NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@"RecordedFile"]]retain];
        
        NSString *recordedFileName = [Utilities getTempSaveFilePathString:_musicName filePath:TempRecordPath];
        _recordedFileName = recordedFileName;
        NSURL *recordedFileNameUrl = [NSURL fileURLWithPath:recordedFileName];
        NSError* error;
        _recorderAudio = [[AVAudioRecorder alloc] initWithURL:recordedFileNameUrl settings:settings error:&error];
        NSLog(@"%@", [error description]);
        if (error)
        {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Sorry"
                                                            message:@"your device doesn't support your setting"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles: nil];
            [alert show];
            return;
        }
        _isRecording = YES;
        [_recorderAudio prepareToRecord];
        _recorderAudio.meteringEnabled = YES;
        [_recorderAudio record];
        _recTimer = [NSTimer scheduledTimerWithTimeInterval:.01f
                                                     target:self
                                                   selector:@selector(timerUpdate)
                                                   userInfo:nil
                                                    repeats:YES];
    }
    else
    {
        //        _isRecording = NO;
        //        [_recTimer invalidate];
        //        _recTimer = nil;
        //
        //        if (_recorderAudio != nil )
        //        {
        //            [_recorderAudio stop];
        //            _recorderAudio = nil;
        //        }
        //        [self encodeBtnClick];
    }
}

- (void) timerUpdate
{
    if (_isRecording)
    {
        int m = _recorderAudio.currentTime / 60;
        int s = ((int) _recorderAudio.currentTime) % 60;
        int ss = (_recorderAudio.currentTime - ((int) _recorderAudio.currentTime)) * 100;
        _recDesLab.text = [NSString stringWithFormat:@"正在录制 %.2d:%.2d / 15:00", m, s];
    }
}


- (void) convertMp3Finish
{
    NSLog(@"sucess convert mp3");
}


#pragma mark CustomPickerBottomViewDelegate

-(void)CustomPickerBottomSelect:(UIButton *)pickerBtn{
    if(!_isRecording){
        return;
    }
    NSInteger tag = pickerBtn.tag - 100;
    [audioPlayer stop];
    [_recTimer invalidate];
    _recTimer = nil;
    [_timer invalidate];
    _timer = nil;
    if (_recorderAudio != nil )
    {
        [_recorderAudio stop];
    }
    if (tag == 0)
    {
        _isRecording = NO;
        
        audioPlayer = nil;
        
        if (_recorderAudio != nil )
        {
            _recorderAudio = nil;
        }
        _mp3FileName = [Utilities getDocmentSaveFilePathString:_musicName filePath:DocRecordPath];
        EQPlayer * player = [[EQPlayer alloc] init];
        SingRecordFinshView *singRecViewCtr = [[SingRecordFinshView alloc]initWithPlayer:player];
        singRecViewCtr.recordMusicPath = _mp3FileName;
        singRecViewCtr.eqcount = seleEq;
        singRecViewCtr.recordMusicName = _musicName;
        
        [self encodeMp3];
        [self.navigationController pushViewController:singRecViewCtr animated:YES];
    }else if (tag == 1)
    {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"友情提示" message:@"录制还没完成 是否重录" delegate:self cancelButtonTitle:@"NO" otherButtonTitles:@"YES", nil];
        [alertView show];
        
        
        
    }else if (tag == 2)
    {
        _isRecording = NO;
        audioPlayer = nil;
        
        if (_recorderAudio != nil )
        {
            _recorderAudio = nil;
        }
        [audioPlayer stop];
        [_recorderAudio stop];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)finishDecod{
    if(_isRecording){
        _isRecording = NO;
        [_recTimer invalidate];
        _recTimer = nil;
        [_timer invalidate];
        _timer = nil;
        
        [audioPlayer stop];
        audioPlayer = nil;
        
        if (_recorderAudio != nil )
        {
            [_recorderAudio stop];
            _recorderAudio = nil;
        }
        _mp3FileName = [Utilities getDocmentSaveFilePathString:_musicName filePath:DocRecordPath];
        EQPlayer * player = [[EQPlayer alloc] init];
        SingRecordFinshView *singRecViewCtr = [[SingRecordFinshView alloc]initWithPlayer:player];
        singRecViewCtr.recordMusicPath = _mp3FileName;
        singRecViewCtr.eqcount = seleEq;
        singRecViewCtr.recordMusicName = _musicName;
        
        [self encodeMp3];
        [self.navigationController pushViewController:singRecViewCtr animated:YES];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        _isRecording = NO;
        
        audioPlayer = nil;
        
        if (_recorderAudio != nil )
        {
            _recorderAudio = nil;
        }
        _mp3FileName = [Utilities getDocmentSaveFilePathString:_musicName filePath:DocRecordPath];
        [[NSFileManager defaultManager] removeItemAtPath:_mp3FileName error:nil];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
        //  [self reBuildView];
    }else if (buttonIndex == 1){
        _isRecording = NO;
        audioPlayer = nil;
        if (_recorderAudio != nil )
        {
            _recorderAudio = nil;
        }
        _mp3FileName = [Utilities getDocmentSaveFilePathString:_musicName filePath:DocRecordPath];
        [[NSFileManager defaultManager] removeItemAtPath:_mp3FileName error:nil];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
        
        [audioPlayer play];
        [_recorderAudio record];
        [self recordSingMusic];
        
        _recTimer = [NSTimer scheduledTimerWithTimeInterval:.01f
                                                     target:self
                                                   selector:@selector(timerUpdate)
                                                   userInfo:nil
                                                    repeats:YES];
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f
                                                  target:self
                                                selector:@selector(showTime)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
